package com.mcr.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mcr.reggie.common.CustomException;
import com.mcr.reggie.dao.CategoryMapper;
import com.mcr.reggie.dao.DishMapper;
import com.mcr.reggie.dao.SetmealMapper;
import com.mcr.reggie.entity.Category;
import com.mcr.reggie.entity.Dish;
import com.mcr.reggie.entity.Setmeal;
import com.mcr.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService{
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Override
    public Page<Category> getPage(int page, int pageSize) {
        Page<Category> pageInfo=new Page<>(page,pageSize);//分页构造器
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        categoryMapper.selectPage(pageInfo,queryWrapper);
        return pageInfo;
    }
    @Override
    public void remove(Long id) {
        LambdaQueryWrapper<Dish> dishQueryWrapper=new LambdaQueryWrapper<>();
        //查询当前分类是否关联一个菜品，如果关联，抛出一个业务异常
        dishQueryWrapper.eq(Dish::getCategoryId,id);
        int dishCount = dishMapper.selectCount(dishQueryWrapper);
        if(dishCount!=0){
            throw new CustomException("当前分类关联了菜品，不能删除");
        }
        LambdaQueryWrapper<Setmeal> setmealQueryWrapper=new LambdaQueryWrapper<>();
        //查询当前分类是否关联一个套餐，如果关联，抛出一个业务异常
        setmealQueryWrapper.eq(Setmeal::getCategoryId,id);
        int setmealCount = setmealMapper.selectCount(setmealQueryWrapper);
        if(setmealCount!=0){
            //已经关联菜品不能删除
            throw new CustomException("当前分类关联了套餐，不能删除");
        }
        //正常删除分类
        super.removeById(id);
        //this代表当前对象本身,super代表当前对象的父类型特征。
    }
    @Override
    public List<Category> getList() {
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort).orderByAsc(Category::getUpdateTime);
        List<Category> categoryList = categoryMapper.selectList(queryWrapper);
        return categoryList;
    }
}
